package main.java.com.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import main.java.com.domain.User;
import main.java.com.util.ConnDb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * !!! Anti-fake label !!!
 * ClassName: Person
 * Package: main.java.com.action
 * Description:
 *
 * @Author 22软件6班 陈彬
 * @Create 2023/12/5 0:46
 * @Version 1.0
 **/

@WebServlet("/PersonServlet")
public class PersonAction extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //将修改个人中心菜单写入到Session
        request.getSession().setAttribute("menuUrl","person-edit.jsp");
        //实现跳转到个人中心修改页面
        //getRequestDispatchar获取转发对象
        request.getRequestDispatcher("/WEB-INF/jsp/shellPage.jsp").forward(request,response);
    }
    //实现个人中心信息的保存
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //配置请求和响应的字符集为UTF-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //创建User实体类
        User user=new User();
        //获取账号loginId
        String loginId=request.getSession().getAttribute("loginId").toString();
        user.setLoginId(loginId);
        //获取用户名
        String userName=request.getParameter("userName");
        user.setUserName(userName);
        //获取手机号
        String phone=request.getParameter("phone");
        user.setPhone(phone);
        //获取密码
        String password=request.getParameter("password");
        user.setPassword(password);
        //获取邮箱
        String email=request.getParameter("email");
        user.setEmail(email);
        //获取注册类型
        String registType=request.getParameter("registType");
        user.setRegistType(registType);
        //获取性别
        String sex=request.getParameter("sex");
        user.setSex(sex);
        //判断密码是否被修改过
        LoginAction lg=new LoginAction();
        //获取数据库中已经存下来的密码作为旧密码
        String oldPassword=lg.queryUserInfoByLoginId(loginId).getPassword();
        String passwordState="false";//默认密码未被修改
        if (!password.equals(oldPassword)){//如果新旧密码不同
            passwordState="true";//表示密码已被修改
        }

        //调用修改保存个人信息注册信息方法
        int num=this.saveUserInfo(user);
        //创建一个jsnobject对象
        JSONObject jsonobject = new JSONObject();
        if (num>0){
            //将用户名写入到Session
            request.getSession().setAttribute("userName",user.getUserName());
            //将JavaBean实体类写入到session
            request.getSession().setAttribute("user",user);
            jsonobject.put("passwordState",passwordState);
            jsonobject.put("code",num);
            jsonobject.put("msg","修改成功！");
        }else {
            jsonobject.put("code",num);
            jsonobject.put("msg","修改失败！");
        }
        //将jsonobject转化为字符串
        String json = JSON.toJSONString(jsonobject);
        //将json字符串写入响应信息中
        response.getWriter().write(json);
    }
    //修改保存个人信息方法
    public int saveUserInfo(User user){
        int num=0;//表示数据是否保存成功，如果num大于0，则保存成功
        try {
            //调用连接数据库方法
            ConnDb db = new ConnDb();
            Connection conn = db.dataBaseConnectionTest();
            //构建SQL语句
            String sql1="UPDATE tb_sys_user SET password=?\n" +
                    "WHERE loginId=?";
            //利用PreparedStatement预处理接口创建对象pstm
            PreparedStatement pstm = conn.prepareStatement(sql1);
            //为占位符?赋值
            pstm.setString(1,user.getPassword());
            pstm.setString(2,user.getLoginId());
            //executeUpdate方法执行插入或更新，返回影响的行数,存入num变量
            num = pstm.executeUpdate();
            if (num>0){//如果num大于0，则数据保存成功
                //构建SQL语句,保存到tb_sys_staff_info
                String sql2="UPDATE tb_sys_staff_info SET\n" +
                        "userName=?,\n" +
                        "phone=?,\n" +
                        "email=?,\n" +
                        "registType=?,\n" +
                        "sex=?,\n" +
                        "updateTime=now()\n" +
                        "WHERE loginId=?";
                //预处理Sql2
                //利用PreparedStatement预处理接口创建对象pstm
                pstm = conn.prepareStatement(sql2);
                //为占位符?赋值
                pstm.setString(1,user.getUserName());
                pstm.setString(2,user.getPhone());
                pstm.setString(3,user.getEmail());
                pstm.setString(4,user.getRegistType());
                pstm.setString(5,user.getSex());
                pstm.setString(6,user.getLoginId());
                //executeUpdate方法执行插入或更新，返回影响的行数,存入num变量
                num = pstm.executeUpdate();
            }
            conn.close();//关闭数据库连接资源
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
        }
}
